package com.bawei.module_mine.ui

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.utils.HistoryDebugUtils
import com.bawei.lib_common.utils.UserUtils
import com.bawei.lib_storage.room.HistoryManager
import com.bawei.module_detail.model.entity.VideoEntity
import com.bawei.module_mine.R
import com.bawei.module_mine.adapter.HistoryVerticalAdapter
import com.google.gson.Gson
import kotlinx.coroutines.launch

@Route(path = "/module_mine/TestHistoryActivity")
class TestHistoryActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_history)
        
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        
        lifecycleScope.launch {
            val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
            val historyList = HistoryManager.getHistoryListByUserId(userId).toMutableList()
            val adapter = HistoryVerticalAdapter(historyList)
            recyclerView.adapter = adapter

            // item点击跳转详情
            adapter.onItemClick = { entity, _ ->
                // 组装VideoEntity
                val video = VideoEntity(
                    avatar_url = entity.authorImg,
                    channelid = "",
                    commentnum = 0,
                    ctime = "",
                    description = entity.content,
                    group_id = "",
                    id = 0,
                    image_url = entity.primaryImg,
                    item_id = entity.videoId,
                    labelIds = "",
                    name = entity.title,
                    playnum = 0,
                    preview_url = entity.primaryImg,
                    publish_time = "",
                    title = entity.title,
                    userid = entity.userId,
                    verifycode = "",
                    videomainimag = entity.primaryImg,
                    videopath = entity.videopath // 这里用真实播放地址
                )
                ARouter.getInstance().build("/detail/DetailActivity")
                    .withString("detail", Gson().toJson(video))
                    .withLong("progress", entity.lastPosition)
                    .navigation()
            }

            // 长按弹窗
            adapter.onItemLongClick = { entity, position ->
                AlertDialog.Builder(this@TestHistoryActivity)
                    .setTitle("操作")
                    .setItems(arrayOf("删除", "取消")) { dialog, which ->
                        if (which == 0) {
                            lifecycleScope.launch {
                                HistoryManager.deleteHistory(entity)
                                adapter.removeAt(position)
                                Toast.makeText(this@TestHistoryActivity, "已删除", Toast.LENGTH_SHORT).show()
                            }
                        }
                        dialog.dismiss()
                    }.show()
            }

            // 删除按钮
            adapter.onDeleteClick = { entity, position ->
                AlertDialog.Builder(this@TestHistoryActivity)
                    .setMessage("确定删除这条历史记录吗？")
                    .setPositiveButton("删除") { dialog, _ ->
                        lifecycleScope.launch {
                            HistoryManager.deleteHistory(entity)
                            adapter.removeAt(position)
                            Toast.makeText(this@TestHistoryActivity, "已删除", Toast.LENGTH_SHORT).show()
                        }
                        dialog.dismiss()
                    }
                    .setNegativeButton("取消", null)
                    .show()
            }

            // 滑动删除
            val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
                override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean = false
                override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                    val pos = viewHolder.adapterPosition
                    val entity = historyList[pos]
                    lifecycleScope.launch {
                        HistoryManager.deleteHistory(entity)
                        adapter.removeAt(pos)
                        Toast.makeText(this@TestHistoryActivity, "已删除", Toast.LENGTH_SHORT).show()
                    }
                }
            })
            itemTouchHelper.attachToRecyclerView(recyclerView)
        }
        // 保留调试方法但不自动调用
        // showDebugInfo()
        // testAddHistory()
        // testGetHistory()
        // testUserHistory()
        // runFullDebug()
    }
    
    /**
     * 显示调试信息
     */
    private fun showDebugInfo() {
        val debugInfo = HistoryDebugUtils.getDebugInfo()
        Log.d("TestHistoryActivity", "调试信息:\n$debugInfo")
        Toast.makeText(this, "调试信息已输出到日志", Toast.LENGTH_SHORT).show()
    }
    
    /**
     * 运行完整调试
     */
    private fun runFullDebug() {
        Log.d("TestHistoryActivity", "运行完整调试...")
        HistoryDebugUtils.debugHistoryFeature()
    }
    
    /**
     * 测试添加历史记录
     */
    private fun testAddHistory() {
        lifecycleScope.launch {
            try {
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                
                Log.d("TestHistoryActivity", "测试添加历史记录，用户ID: '$userId'")
                
                HistoryManager.addVideoHistory(
                    userId = userId,
                    title = "测试视频标题_${System.currentTimeMillis()}",
                    primaryImg = "https://example.com/image.jpg",
                    content = "这是一个测试视频的描述内容",
                    authorImg = "https://example.com/avatar.jpg",
                    authorName = "测试作者",
                    progress = 50,
                    lastPosition = 0L,
                    videoId = "test_video_id",
                    videopath = "https://example.com/test_video.mp4"
                )
                Toast.makeText(this@TestHistoryActivity, "添加历史记录成功，用户ID: $userId", Toast.LENGTH_SHORT).show()
                Log.d("TestHistoryActivity", "添加历史记录成功，用户ID: $userId")
            } catch (e: Exception) {
                Toast.makeText(this@TestHistoryActivity, "添加历史记录失败: ${e.message}", Toast.LENGTH_SHORT).show()
                Log.e("TestHistoryActivity", "添加历史记录失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 测试获取历史记录
     */
    private fun testGetHistory() {
        lifecycleScope.launch {
            try {
                val historyList = HistoryManager.getHistoryList()
                Toast.makeText(this@TestHistoryActivity, "获取所有历史记录成功，数量: ${historyList.size}", Toast.LENGTH_SHORT).show()
                Log.d("TestHistoryActivity", "获取所有历史记录成功，数量: ${historyList.size}")
                
                historyList.forEach { history ->
                    Log.d("TestHistoryActivity", "历史记录: ${history.title} - ${history.authorName} - 用户ID: '${history.userId}'")
                }
            } catch (e: Exception) {
                Toast.makeText(this@TestHistoryActivity, "获取历史记录失败: ${e.message}", Toast.LENGTH_SHORT).show()
                Log.e("TestHistoryActivity", "获取历史记录失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 测试用户历史记录功能
     */
    private fun testUserHistory() {
        lifecycleScope.launch {
            try {
                val userId = UserUtils.getCurrentUserId()
                if (userId.isNotEmpty()) {
                    val userHistoryList = HistoryManager.getHistoryListByUserId(userId)
                    Toast.makeText(this@TestHistoryActivity, "获取用户历史记录成功，用户ID: $userId, 数量: ${userHistoryList.size}", Toast.LENGTH_SHORT).show()
                    Log.d("TestHistoryActivity", "获取用户历史记录成功，用户ID: $userId, 数量: ${userHistoryList.size}")
                    
                    userHistoryList.forEach { history ->
                        Log.d("TestHistoryActivity", "用户历史记录: ${history.title} - ${history.authorName}")
                    }
                } else {
                    // 测试默认用户ID
                    val defaultUserId = UserUtils.getDefaultUserId()
                    val userHistoryList = HistoryManager.getHistoryListByUserId(defaultUserId)
                    Toast.makeText(this@TestHistoryActivity, "获取默认用户历史记录成功，用户ID: $defaultUserId, 数量: ${userHistoryList.size}", Toast.LENGTH_SHORT).show()
                    Log.d("TestHistoryActivity", "获取默认用户历史记录成功，用户ID: $defaultUserId, 数量: ${userHistoryList.size}")
                    
                    userHistoryList.forEach { history ->
                        Log.d("TestHistoryActivity", "默认用户历史记录: ${history.title} - ${history.authorName}")
                    }
                }
            } catch (e: Exception) {
                Toast.makeText(this@TestHistoryActivity, "获取用户历史记录失败: ${e.message}", Toast.LENGTH_SHORT).show()
                Log.e("TestHistoryActivity", "获取用户历史记录失败: ${e.message}", e)
            }
        }
    }
} 